package com.AiEnglishApp.backend.controller;

import com.AiEnglishApp.backend.entity.User;
import com.AiEnglishApp.backend.mapper.UserMapper;
import com.AiEnglishApp.backend.response.ResponseResult;
import com.AiEnglishApp.backend.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/{id}")
    public ResponseResult<User> getUserById(@PathVariable Long id) {
        // 尝试从 Redis 中获取用户信息
        String key = "user:" + id;
        User user = (User) redisTemplate.opsForValue().get(key);

        if (user == null) {
            // 如果 Redis 中没有，从数据库中获取
            user = userMapper.findById(id);
            if (user != null) {
                // 将用户信息存储到 Redis
                redisTemplate.opsForValue().set(key, user);
            } else {
                return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "用户不存在");
            }
        }
        return ResponseResult.success(user);
    }

    @GetMapping
    public ResponseResult<List<User>> getAllUsers() {
        List<User> users = userMapper.findAll();
        return ResponseResult.success(users);
    }

    @PostMapping
    public ResponseResult<Integer> createUser(@RequestBody User user) {
        int result = userMapper.insert(user);
        if (result > 0) {
            // 将用户信息存储到 Redis
            String key = "user:" + user.getId();
            redisTemplate.opsForValue().set(key, user);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "创建用户失败");
        }
    }

    @PutMapping
    public ResponseResult<Integer> updateUser(@RequestBody User user) {
        int result = userMapper.update(user);
        if (result > 0) {
            // 更新 Redis 中的用户信息
            String key = "user:" + user.getId();
            redisTemplate.opsForValue().set(key, user);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "更新用户失败");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Integer> deleteUser(@PathVariable Long id) {
        int result = userMapper.deleteById(id);
        if (result > 0) {
            // 删除 Redis 中的用户信息
            String key = "user:" + id;
            redisTemplate.delete(key);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "删除用户失败");
        }
    }
}